/*
 This file 'FormValidator' is part of Firebird Integrated Solution 1.0

 Copyright (c) 2014 Lincong

 Contact:  
 Email: lincong1987@gmail.com

 QQ: 159257119

 See Usage at http://www.jplatformx.com/firebird

 Create date: 2014-06-19 15:52
 */

define(function (require, exports, module) {

	require("Firebird.ui.Component");
	require("../niceValidator/js/validator");

	/**
	 * Firebird.ui.FormValidator
	 * @class Firebird.ui.FormValidator
	 * @extends Firebird.ui.Component
	 * @link <a href="http://niceue.com/validator">http://niceue.com/validator</a>
	 */
	Firebird.define("Firebird.ui.FormValidator", {
		extend: "Firebird.ui.Component",
		statics: {
			_uuid: 0,
			uuid: function () {
				return this._uuid++;
			}
		},
		config: {
			renderTo: null,
			instanceId: null,

			onSuccess: null,
			onError: null,
			onValidation: null
		},
		/**
		 *
		 * @returns {{}}
		 */
		defaults: function () {
			return {};
		},
		/**
		 * initialize after constructor
		 * @private
		 */
		_init: function () {
			var me = this;
			//me.form = $(me.id);

			me.instance = $(me.getRenderTo());
			me.options = $.extend({}, me.defaults());
			me.validator = me.instance.validator(me.options).data("validator");

			// 加钩子
			me.instance.on("validation", function (e, current) {
				me.onValidation.apply(me, [e, current]);
			});

			me.instance.on("invalid.form", function (e, form, errors) {
				me.onError.apply(me, [e, form, errors]);
			});

			me.instance.on("valid.form", function (e, form) {
				me.onSuccess.apply(me, [e, form]);
			});
		},
		/**
		 * getResult
		 * @returns {Boolean}
		 */
		getResult: function (callback) {
			this.doValidate();
			return this.isFormValid();
		},
		/**
		 * doValidate
		 * @returns {Firebird.ui.FormValidator}
		 */
		doValidate: function () {
			this.instance.trigger("validate");
			return this;
		},
		/**
		 * onSuccess
		 */
		onSuccess: function () {
		},
		/**
		 * onError
		 */
		onError: function () {
		},
		/**
		 * onValidation
		 */
		onValidation: function () {
		},
		/**
		 * isFormValid 当确定验证结果的时候，返回true或者false，当不确定的时候返回undefined
		 * @returns {Boolean}
		 */
		isFormValid: function () {
			return this.validator.isFormValid();
		},
		/**
		 * cleanUp
		 * @returns {Firebird.ui.FormValidator}
		 */
		cleanUp: function () {
			this.validator.cleanUp();
			return this;
		},
		/**
		 * destroy
		 * @returns {Firebird.ui.FormValidator}
		 */
		destroy: function () {
			this.validator.destroy();
			return this;
		},
		/**
		 * holdSubmit
		 * @param hold
		 * @returns {Firebird.ui.FormValidator}
		 */
		holdSubmit: function (hold) {
			this.validator.holdSubmit.apply(this.validator, [hold]);
			return this;
		},
		/**
		 * 测试某个元素是否符合某个规则，参数 ruleName 可以带参数，例如：this.test(element, "range[0~100]")
		 * @param: {Element} element 字段元素
		 * @param: {String} ruleName 规则名字
		 * @returns {*|boolean}
		 * @example:
		 * var formValidator = new Firebird.ui.FormValidator({
         *      rules: {
         *          // 自定义规则：符合用户名、手机号或者邮箱规则都算通过
         *          // 注意：第一个test是正则的方法，后面两个是this.test()是当前实例的方法
         *          loginName: function(element) {
         *              return /^[a-zA-Z]\w{3,}/.test(element.value)
         *                     || this.test(element, "mobile")===true
         *                     || this.test(element, "email")===true
         *                     || '请填写用户名、手机号或者邮箱';
         *          }
         *      },
         *      fields: {
         *          "loginName": "required; loginName",
         *          "password": "required; password"
         *      }
         *  });
		 */
		test: function (element, ruleName) {
			return this.validator.test(element, ruleName);
		},
		/**
		 * 用来显示服务器的验证消息。(提交表单并且服务器验证完毕后，返回一个name为键、msg为value的json传入此方法中)
		 * @param map
		 * @returns {Firebird.ui.FormValidator}
		 * @example:
		 * formValidator.mapMsg({
         *      username: '用户名已被使用',
         *      password: '密码太弱了'
         * });
		 */
		mapMsg: function (map) {
			this.validator.mapMsg(map);
			return this;
		},
		/**
		 * 在一个字段元素上显示一条消息
		 * @param element
		 * @param map
		 * @returns {Firebird.ui.FormValidator}
		 * @example
		 * <pre>
		 * // 给id为“mobile”的元素显示一条错误消息
		 * formValidator.showMsg('#mobile', {
         *      type: "error",
         *      msg: "手机号已存在"
         * });
		 * </pre>
		 */
		showMsg: function (element, map) {
			this.validator.showMsg.apply(this.validator, [element, map]);
			return this;
		},
		/**
		 * 隐藏一个字段元素上的消息
		 * @param element
		 * @param map
		 * @returns {Firebird.ui.FormValidator}
		 * @example
		 * <pre>
		 * // 隐藏id为“mobile”的的元素的消息
		 * formValidator.hideMsg('#mobile');
		 * </pre>
		 */
		hideMsg: function (element, map) {
			this.validator.hideMsg.apply(this.validator, [element, map]);
			return this;
		},
		/**
		 * 自定义消息，可用来动态改变某个表单验证的消息（优先于内置、全局、传参的消息）
		 * @returns {Firebird.ui.FormValidator}
		 * @example
		 * <pre>
		 * // 动态更改当前实例的错误消息
		 * formValidator.setMsg({
         *      username: '用户名已被使用',
         *      password: '密码太弱了'
         * });
		 * </pre>
		 */
		setMsg: function (map) {
			this.validator.setMsg.apply(this.validator, [map]);
			return this;
		},
		/**
		 * 自定义规则，可用来动态改变某个表单验证的规则（优先于内置、全局、传参的规则）
		 * @returns {Firebird.ui.FormValidator}
		 */
		setRule: function (rule) {
			//this.validator.setRule.apply(this.validator, [rule]);
			$.validator.config({
				rules: rule
			});
			return this;
		},
		setOptions: function (options) {
			$.validator.config(options);
			return this;
		},
		/**
		 *
		 * 更新一个字段信息.
		 * 如果是新字段就等于添加了一个字段；
		 * 如果field===null，并且实例中存在字段key，则会删除字段key（不验证key字段）
		 * @param key {String} key 字段名
		 * @param field {Object} field 字段信息
		 * @returns {Firebird.ui.FormValidator}
		 * @example
		 * <pre>
		 * // 动态更改字段name为“username”的验证规则
		 * formValidator.setField("username", "用户名:required;username;");
		 * </pre>
		 */
		setField: function (key, field) {
			this.validator.setField.apply(this.validator, [key, field]);
			return this;
		},
		/**
		 * 批量更新字段信息.
		 * 如果是新字段就等于添加了一个字段；
		 * 如果某个字段的值为null，并且实例中存在该字段，则会删除该字段（不验证该字段）
		 * @param fields
		 * @returns {Firebird.ui.FormValidator}
		 * @example
		 * <pre>
		 * // 批量更改字段的验证规则
		 * formValidator.setField({
         *      party: null,                // 将不再验证party字段
         *      organization: 'required'    // 更改organization字段的验证规则
         * });
		 * </pre>
		 */
		setFields: function (fields) {
			this.validator.setField.apply(this.validator, [fields]);
			return this;
		},
		/**
		 *
		 * @param options
		 * @returns {Firebird.ui.FormValidator}
		 */
		setTheme: function (options) {
			this.validator.setTheme.apply(this.validator, [options]);
			return this;
		}

	});

	module.exports = Firebird.ui.FormValidator;

});